package com.ews.onlineexchange.service.schedule;

import java.util.Calendar;

import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import org.hibernate.CacheMode;
import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;

import com.ews.onlineexchange.model.Trade;
import com.ews.onlineexchange.model.TradeRating;
import com.ews.onlineexchange.service.TradeHome;
import com.ews.onlineexchange.service.TradeRatingHome;

@Singleton
@Startup
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class TradeAutoRatingTimer {

	@Resource
	TimerService timerService;
	
	@Inject
	EntityManager entityManager;
	
	@Inject
	TradeRatingHome tradeRatingHome;
	
	@Inject
	TradeHome tradeHome;
//	
////	@PostConstruct
//	public void init() {
//		ScheduleExpression schedule = new ScheduleExpression();	
//		schedule.hour(5);
//		timerService.createCalendarTimer(schedule, new TimerConfig("tradeAutoRateTimer", false));
//		
////		check();
//	}
	
//	private static final String QUERY_ALL_OVERDUE_RATE_TRADE_EQL = ""
//			+ "	SELECT			bulletin.successTrade"
//			+ "	FROM			Bulletin bulletin "
//			+ "	WHERE			bulletin.done = false"
//			+ "	AND				bulletin.applyDone = true"
//			+ "	AND				bulletin.applyDoneTime > :_5DaysLater "
//			+ "	AND				bulletin.cancelled = false	";
////	@Timeout
//	@Schedule(hour="5", minute="0", second="0", info = "tradeAutoRateTimer", persistent = false)
//	public void check() {		
//		Session session = entityManager.unwrap( Session.class );
//		ScrollableResults sr = session.createQuery(QUERY_ALL_OVERDUE_RATE_TRADE_EQL).setCacheMode( CacheMode.IGNORE )
//	        .scroll( ScrollMode.FORWARD_ONLY );
//		Calendar cal = Calendar.getInstance();
//		cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + 5);
//		query.setParameter("_5DaysLater", cal.getTime());
//		ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);
//		
//		while (sr.next()) {
//			Trade st = (Trade) sr.get(0);
//			tradeHome.setInstance(st);
//			TradeRating tradeRating = new TradeRating();
//			tradeRating.setRateText("系统默认评价");
//			tradeRatingHome.setInstance(tradeRating);
//			tradeRatingHome.saveAndFlush();
//		}
//	}
}
